package com.theatre.userservice.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.theatre.userservice.annotation.RequirePermission;
import com.theatre.userservice.Controller.contxet.BaseContext;
import com.theatre.userservice.mapper.PublisherMapper;
import com.theatre.userservice.model.dto.PublisherDTO;
import com.theatre.userservice.model.entity.Publisher;
import com.theatre.userservice.model.vo.PublisherVO;
import com.theatre.userservice.model.vo.ScriptVO;
import com.theatre.userservice.model.vo.utils.FileUploadUtil;
import com.theatre.userservice.service.PublisherService;
import com.theatre.userservice.model.vo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/publisher")
@Tag(name = "发行商接口", description = "提供发行商相关的接口")
public class PublisherController  {

    @Autowired
    private PublisherMapper publisherMapper;
    @Autowired
    private PublisherService publisherService;
    @Value("${upload.base-dir}")
    private String uploadBaseDir;

    @RequirePermission("content:manage")
    @PostMapping("/insert")
    @Operation(summary = "新增发行商", description = "新增发行商")
    public Result<Long> insert(@RequestBody PublisherDTO publisherDTO) {
        // 校验参数（删除超级管理员）
        Long currentUserId = BaseContext.getUserId();
        //TODO: 超级管理员校验逻辑删除
        if (currentUserId == null || currentUserId == 3 || currentUserId == 4) {
            return Result.error("没有资格注册成为发行商");
        }
        // 参数校验
        if (publisherDTO.getName() == null || publisherDTO.getName().isEmpty()) {
            return Result.error("发行商名称不能为空");
        }
        if (publisherDTO.getPhone() == null || publisherDTO.getPhone().isEmpty()) {
            return Result.error("联系电话不能为空");
        }
        Publisher publisher = publisherDTO.toEntity();
        publisher.setUserId(currentUserId);
        publisher.setStatus(0); // 待审核状态
        // 保存到数据库
        int insertResult = publisherMapper.insert(publisher);
        if (insertResult <= 0) {
            return Result.error("新增发行商失败");
        }
        return Result.success(publisher.getId());
    }

    // 上传营业执照，要求角色为发行商
    @RequirePermission("content:manage")
    @PostMapping("/uploadLicense")
    @Operation(summary = "上传营业执照", description = "上传营业执照")
    public Result<String> uploadLicense(@RequestParam("file") MultipartFile file) {
        Long currentUserId = BaseContext.getUserId();

        if (currentUserId == null || currentUserId == 3 || currentUserId == 4) {
            return Result.error("发行商才有资格上传营业执照");
        }

        if (file == null || file.isEmpty()) {
            return Result.error("请上传营业执照文件");
        }

        try {
            String relativePath = FileUploadUtil.saveFile(file, uploadBaseDir, "licenses");

            Publisher publisher = new Publisher();
            publisher.setUserId(currentUserId);
            publisher.setLicenseFile(relativePath);

            int updated = publisherMapper.update(publisher,
                    new LambdaUpdateWrapper<Publisher>().eq(Publisher::getUserId, currentUserId));

            if (updated <= 0) {
                return Result.error("更新营业执照失败");
            }

            return Result.success(relativePath);
        } catch (Exception e) {
            throw new RuntimeException("上传营业执照失败", e);
        }
    }
    @GetMapping("/{id}")
    @RequirePermission("content:manage")
    @Operation(summary = "显示发行商信息", description = "根据发行商id显示发行商信息")
    public Result<PublisherVO> showShop(@PathVariable("id") Long id) {
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null || currentId == 3 || currentId == 4) {
            return Result.error("无有资格查看发行商信息");
        }
        // 查询商户信息
        Publisher publisher = publisherMapper.selectById(id);
        if (publisher == null) {
            return Result.error("发行商不存在");
        }
        // 转换成VO
        PublisherVO publisherVO = new PublisherVO();
        BeanUtils.copyProperties(publisher, publisherVO);
        return Result.success(publisherVO);
    }
    @GetMapping("/list/{id}")
    @RequirePermission("content:manage")
    @Operation(summary = "显示发行商所有的剧本", description = "显示所有发行商的剧本信息")
    public Result<List<ScriptVO>> list(@PathVariable("id") Long id) {
        if (publisherMapper.selectById(id).getStatus() != 1) {
            return Result.error("发行商审核未通过");
        }
        List<ScriptVO> publisherVO = publisherService.selectScriptByPublisherId(id);
        return Result.success(publisherVO);
    }

    @GetMapping("/user")
    @RequirePermission("content:manage")
    @Operation(summary = "根据用户ID查询发行商", description = "根据当前登录用户的ID查询所属发行商信息")
    public Result<PublisherVO> getPublisherByUserId() {
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null || currentId == 3 || currentId == 4) {
            return Result.error("没有资格查看发行商信息");
        }
        Long currentUserId = BaseContext.getUserId();
        Publisher publisher = publisherMapper.selectOne(
                new QueryWrapper<Publisher>().eq("user_id", currentUserId)
        );
        if (publisher == null) {
            return Result.error("未找到对应的发行商信息,请先注册门店");
        }
        PublisherVO publisherVO = new PublisherVO();
        BeanUtils.copyProperties(publisher, publisherVO);
        return Result.success(publisherVO);
    }
}
